package com.qianfeng.log.es.service.impl;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.log.es.service.EsService;
import com.qianfeng.log.web.pojo.SysOperLog;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Jackiechan on 2022/2/8/14:40
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Service
public class EsServiceImpl implements EsService {

    private RestHighLevelClient highLevelClient;


    private ObjectMapper objectMapper;

    @Value("${elasticsearh.indexName}")
    private String indexName;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setHighLevelClient(RestHighLevelClient highLevelClient) {
        this.highLevelClient = highLevelClient;
    }

    @Override
    public void addDoc(String indexName,SysOperLog sysOperLog) {
        IndexRequest request = new IndexRequest(indexName);
        try {
            request.source(objectMapper.writeValueAsString(sysOperLog), XContentType.JSON);
            highLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void createIndex(String indexName) {
        if (!indexExist(indexName)) {
            //如果不存在,就创建索引
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            try {
                highLevelClient.indices().create(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean indexExist(String indexName) {
        GetIndexRequest request = new GetIndexRequest(indexName);
        boolean exists = false;
        try {
            exists = highLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exists;
    }

    @Override
    public  List<Map> searchByTitle(String value) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchQuery("title", value));
        SearchRequest searchRequest = new SearchRequest(indexName).source(sourceBuilder);
        try {
            SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] searchHits = response.getHits().getHits();
//            for (SearchHit hit : searchHits) {
//                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
//            }
            if (searchHits != null) {
                List<Map> mapList = Arrays.asList(searchHits).stream().map(SearchHit::getSourceAsMap).collect(Collectors.toList());
                return mapList;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @PostConstruct
    public void init() {
        createIndex(indexName);
    }
}
